
import { createElement, useEffect, useRef, useState, useMemo, forwardRef } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { Button, Checkbox, Select, Popover, Form, notification, Radio, Row, Col, message } from 'antd';
import { cloneDeep, find } from 'lodash';
import moment from 'moment';
import IconFont from '@/components/IconFont';
import EditFilterModal from '@/pages/OrderModule/orderList/components/OrderList/components/RightAction/EditColumns/EditFilter.jsx';
import { DownOutlined, ReloadOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import Typography from '@/pages/OrderModule/common/components/Typography';
import { useResize } from '@/pages/OrderModule/common/hooks/useResize';
import { SelectBatchInput } from '../components/SelectBatchInput';
import { initFilterConfigList } from './constant.js';
// import initFilterConfigList from './FilterItemsRender.jsx';
import { QueryButton } from '../components/QuicklyQuery/queryButton.jsx'
import FieldWrapper from '../components/FieldWrapper';
import SearchAddress from '../components/OrderSn/SearchAddress';
import FilterItem from '../filterItem.jsx';
import allComponentsMap from './FilterItemsRender.jsx';
import SelectActions from "@/pages/OrderModule/common/components/SelectAction";
import ErrorTypeManageModal from "@/views/components/ErrorTypeManage";
import Api from '../../Actions/service.js';
import { getQuickSearchList, addQuickSearchOp, delQuickSearchOp, updateSortOp } from '@/pages/OrderModule/common/hooks/useConfig/services';
import { useQuiteSearch } from '../components/QuicklyQuery';
import styles from './index.module.less';
import QuickSearchModal from './QuickSearchModal';
import HotGoodsSearch from './HotGoodsSearch';
import DynamicStoreSelectKX from '@/components/DynamicStoreSelectKX';
import { queryExpressList } from '../components/Express/server';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import { getFieldConfig } from '../../OrderList/services.js';

const dateFormat = "YYYY-MM-DD HH:mm:ss";

  // 格式化剩余发货时间
  const formatEcLastDeliveryTime = (value) => {
    if (value === "1") {
      // 已超时
      return { max: new Date().getTime()}
    }else if (value === "2") {
      // 12小时内
      return { min: new Date().getTime(), max: new Date().getTime() + 12 * 60 * 60 * 1000}
    }else if (value === "3") {
      // 24小时内
      return { min: new Date().getTime(), max: new Date().getTime() + 24 * 60 * 60 * 1000}
    } else if (value === "4") {
      // 3天内
      return { min: new Date().getTime(), max: new Date().getTime() + 3 * 24 * 60 * 60 * 1000}
    } else {
      return {  }
    }
  }

export const SelectBtn = ({ isSelect, children, onClick, style = {} }) => {
  return (<div className={`${styles.selectBtnWrapper} ${isSelect ? styles.isSelect : ''}`} onClick={onClick} style={{...style}}>
    {children}
  </div>)
}

const initParams = {
  isLimit: true,
  qmErpSnArr: 'qmErpSnArr',
  provinceIdArr: 'provinceIdArr',
  goodsName: 'goodsName',
  goodsSku: 'skuCode',
  goodsSpu: 'spuCode',
  totalAmount: 'totalAmount',
  isOrderTypeOr: false,
  isLabelOr: true,
  sellerMessage: 'sellerMessage',
  buyerMessage: 'buyerMessage',
  orderRemark: 'orderRemark',
  timeType: 'ecPayTime'
}

export default ({ type, staticNumberObj = {}, searchForm, onResize, handleSearch, getHotStatisticsFunc }) => {

  const [form] = Form.useForm();
  const [expand, setExpand] = useState(true);

  const [filterList, setFilterList] = useState(initFilterConfigList);
  const [items, setItems] = useState([]);
  const [visible, setVisible] = useState(false);

  const [errorList, setErrorList] = useState([]);
  const [checkedList, setCheckedList] = useState([]);
	const [openError, setOpenError]=useState(false);
  const [filter, setFilter] = useState([]);
  const [quickSearchId, setQuickSearchId] = useState('');
  const [bigScreen, setBigScreen] = useState(false);
  const [logisticSelect, setLogisticSelect] = useState(0);

  const [restKey, setResetKey] = useState(0);

  const stageParams = useRef({...initParams});
  const originFormData = useRef({});//原始表单数据
  const warehouseGroup = useRef({});
  const allQuickSearch = useRef([]);

	const { el, width: screenWidth } = useResize();
  const { data: resp, fetch: fetchExpressList } = useFetch(queryExpressList, {}, false);
  
  useEffect(()=>{
    handelGetFilterConfig();
    handelGetConfigList();
    fetchExpressList({ type: 1 });
  }, [])

  useEffect(()=>{
    if(type == 2){
      form.setFieldsValue({
        warehouseIdArr: warehouseGroup.current.zifaIds
      })
    }
    if(allQuickSearch.current?.length){
      setItems(allQuickSearch.current.filter(item=> JSON.parse(item.param)?.pageType == type));
    }
    // setFilter(type == 1 ? ['auditCheck', 'errorIdArr'] : []);
    setFilter([]);
    logisticSelect && setLogisticSelect(0);
    quickSearchId && setQuickSearchId('');
  }, [type])

  useEffect(()=>{
    onFinish();
  }, [filter])

  useEffect(()=>{
		onResize();
	}, [expand])

  useEffect(()=>{
		setBigScreen(screenWidth > 1530)
	}, [screenWidth])

  // 快递公司列表
  const companyListIds = useMemo(() => {
    if (resp?.data?.length) {
      return resp?.data?.map((item) => item.baseExpressId);
    } 
    return [];
  }, [resp]);

  //获取异常原因
  const getErrorReasonFunc = async () => {
    const { success, data } = await Api.getErrorReason();
    if (success && data?.length) {
      const list = staticNumberObj.errorList;
      data.map(item=>{
        const obj = find(list, ['errorId', item.id]);
        item.count = obj?.count;
      })
      setErrorList(data);
    }
  }

  //表单配置
  const handelGetFilterConfig = async () => {
    const { data, success} = await getFieldConfig({ code: 'hotFilter' });
    if(success && data?.param){
      const config = JSON.parse(data.param);
      filterList.map(item=>{
        const field = item.name;
        item.checked = config[field] == undefined ? true : config[field];
      })
      setFilterList([...filterList])
    }
  }

  //快捷查询配置列表
  const handelGetConfigList = async () => {
    const { data, success} = await getQuickSearchList({ page: 'hot-order' });
    if(success){
      allQuickSearch.current = data;
      setItems(data.filter(item=> JSON.parse(item.param)?.pageType == type))
    }
  }

  //快捷查询删除
  const handelDelete = async (configId) => {
    const { data, success} = await delQuickSearchOp({ configId });
    if(success){
      handelGetConfigList();
    }
  }

  const statusObj = useMemo(()=>{
    if(errorList?.length){
      if(errorList?.length == checkedList?.length){
        return { checked: true}
      }else if(checkedList?.length){
        return { indeterminate: true}
      }
    }
    return {}
  }, [errorList, checkedList])

  const onFinish = (bool) => {
    if(stageParams.current.isLimit) return;
    if(bool && quickSearchId){
      setQuickSearchId('');
    }
    const values = form.getFieldsValue();
    Object.keys(values).map(item=>{
      if(typeof values[item] == 'undefined'){
        delete values[item];
      }
      // else if(Array.isArray(values[item]) && !values[item]?.length)  delete values[item];
    })
    let params = { pageType: type };
    //spec 奇门单号 发货仓 logisticsCompanyId
    ['snArr', 'outOrderSnArr', 'qmErpSnArr', 'logisticsNoArr', 'uniqueCodeArr'].map(item=>{
      if(values[item]){ 
        params[item == 'qmErpSnArr' ? stageParams.current.qmErpSnArr : item] = values[item]?.split(',');
        delete values[item];
      };
    })
    //spec 支付状态
    if(type == 2 && filter.includes('unpayCheck')){
      params.dfNoPay = true;
      params.payStateArr = values.payStateArr?.length ? [...new Set([...values.payStateArr, 0])] : [0];
      delete values.payStateArr;
    }
    //spec 打印状态
     if(type == 2 && ['printCheck0','printCheck1','printCheck2'].includes(filter[0])){
      const topState =  Number(filter[0].replace('printCheck', '')), selectState = values.printState;
      if(selectState){
        if(topState == selectState){
          params.printState = topState;
        }else if(topState == 0 || selectState == 0){
          params.printState = 3;
        }else{
          params.printState = 2;
        }
      }else{
        params.printState = topState;
      }
      delete values.printState;
    }
    //spec 省市区
    const provinceIdArr = values.provinceIdArr;
    if(provinceIdArr){
      const arr1 = [], arr2 = [], arr3 = [];
      provinceIdArr.map(leval1=>{
        arr1.push(leval1.id);
        leval1.childs?.map(leval2=>{
          arr2.push(leval2.id);
          leval2.childs?.map(leval3=>{
            arr3.push(leval3.id);
          })
        })
      })
      params.provinceIdArr = arr1;
      params.cityIdArr = arr2;
      params.districtIdArr = arr3;
      // params[stageParams.current.provinceIdArr] = provinceIdArr;
      delete values.provinceIdArr;
    }
    //spec 商品名称
    if(values.goodsName){
      params[stageParams.current.goodsName] = values.goodsName;
      delete values.goodsName;
    }
    //spec 商品编码
    if(values.goodsSku){
      // params[stageParams.current.goodsSku] = values.goodsSku;
      params.skuSearchFlag = stageParams.current.goodsSku == 'skuCodeAccurate'
      params.sysSkuCode = values.goodsSku
      delete values.goodsSku;
    }
    //spec 款式编码
    if(values.goodsSpu){
      // params[stageParams.current.goodsSpu] = values.goodsSpu;
      params.spuSearchFlag = stageParams.current.goodsSpu == 'spuCodeAccurate'
      params.sysSpuCode = values.goodsSpu
      delete values.goodsSpu;
    }
    //spec 采购价 会员价
    const unitPrice = values?.unitPrice
    if(unitPrice){
      if(unitPrice == '0.01'){
        params.storeGoodsPrice = Number(unitPrice);
      }else{
        params.isVipGoods = Number(unitPrice);
      }
      delete values.unitPrice;
    }
    //spec 订单类型
    if(values.orderTypeArr?.length){
      const isOrderTypeOr = stageParams.current.isOrderTypeOr;
      params.isOrderTypeOr = isOrderTypeOr == undefined ? false : isOrderTypeOr;
      const orderTypeMap = {};
      values.orderTypeArr.map(item=>{
        orderTypeMap[item] = true;
      });
      params.orderTypeMap = orderTypeMap;
      delete values.orderTypeArr;
    }
    //spec 货品总数 总金额 采购价 重量
    ['totalGoodsNum', 'skuTotal', 'totalAmount', 'weight'].map(field=>{
      const numberObj = values[field];
      if(numberObj){
        Object.keys(numberObj).map(item=>{
          if(numberObj[item]){
            params[item] = numberObj[item];
          }
        })
        delete values[field];
      }
    })
    if(values.logisticsCompanyId?.length){
      if(values.logisticsCompanyId.includes(-9999)){
        params.allLogisticsCompanyId = companyListIds;
      }
    }

    //spec 卖家备注 买家留言 订单备注
    const noteArr = ['sellerMessage', 'buyerMessage', 'orderRemark'];
    noteArr.map(field=>{
      const value = stageParams.current[field], requiredField = 'had' + field.replace(field.charAt(0), field.charAt(0).toUpperCase());
      if(value === false){
        params[requiredField] = false;
      } else if(value === true) {
        params[requiredField] = true;
      } else if(values[field]){
        params[requiredField] = true;
      }
    })

    //spec 嵌套
    const nestArr = ['sysSkuCodeArr', 'containLabelIdArr', 'excludeLabelIdArr'];
    nestArr.map(field=>{
      const value = values[field];
      if(value){
        console.log(value, 'sdffdfsdf')
        Object.assign(params, value);
        delete values[field];
      }
    })

    //filter 
    const stateMaps = {'auditCheck': 10, 'errorIdArr': 30, 'mergeCheck': 51, 'splitCheck': 52};
    filter.map(item=>{
      if(Object.keys(stateMaps).includes(item)){//订单状态
        params.stateArr = [...new Set([...(params.stateArr|| []), stateMaps[item]])];
        if(item == 'errorIdArr'){//异常订单
          params.errorIdArr = checkedList;
        }
      }else if(item == 'shipTimeOutCheck'){
        params[item] = true;
        params.timeOutSetting = stageParams.current.shipTimeOutCheck || 12;
      }else if(item == 'pickUpTimeOutCheck'){
        params[item] = true;
        params.pickUptimeOutSetting = stageParams.current.pickUpTimeOutCheck || 6;
      }else if(item =='isMatchCheck'){
        const isMatch = values.isMatch, hasValue = isMatch || isMatch === 0;
        if(hasValue){
          params.isMatch = isMatch === 0 ? 0 : -1;
        }else{
          params.isMatch = 0;
        }
        params.noMatchCheck = true;
        delete values.isMatch;
      }else{
        params[item] = true;
      }
    })

    if(values.time){
      params[stageParams.current.timeType + 'Min'] = moment(values.time[0]).valueOf();
      params[stageParams.current.timeType + 'Max'] = moment(values.time[1]).valueOf();
      delete values.time;
    }

    if(values.ecLastDeliveryTime){
      const { min, max } = formatEcLastDeliveryTime(values.ecLastDeliveryTime);
      params.ecLastDeliveryTimeMin = min;
      params.ecLastDeliveryTimeMax = max;
      delete values.ecLastDeliveryTime;
    }

    console.log(params, values, 66);
    handleSearch({
      ...params,
      ...values
    })
  };

  //固定筛选
  const handleChangeFilter = (key) => {
    if (filter?.includes(key)) {
      setFilter(filter.filter(item => item != key));
    } else {
      const sharedArr = ['auditCheck', 'errorIdArr', 'splitCheck', 'mergeCheck'],
        isExit = filter.some(item => sharedArr.includes(item));
      if (type == 1 && isExit && sharedArr.includes(key)) {
        setFilter([...filter, key]);
      } else {
        setFilter([key]);
      }
    }
  }
  
  const EditFilterModalProps = {
    code: 'hotFilter',
    filterList,
    initFilterList: initFilterConfigList,
    handleOk(showList){
      // console.log(showList, 111111, searchForm)
      for(let item of showList) {
        if(item.name == 'goodsSpu' && !item.checked) {
          form.setFieldsValue({
            goodsSpu: '', // 重置表单输入框
          })
          searchForm.spuSearchFlag = false
          searchForm.sysSpuCode = ''
          handleSearch(searchForm)
        }
        if(item.name == 'goodsSku' && !item.checked) {
          form.setFieldsValue({
            goodsSku: '',
          })
          searchForm.skuSearchFlag = false
          searchForm.sysSkuCode = ''
          handleSearch(searchForm)
        }
      }
      setFilterList(showList);
      setVisible(false);
      // onReset()
    },
    handleCancel(){
      setVisible(false);
    },
  }

  const ErrorTypeManageProps = {
		handleOk() {
			setOpenError(false);
		},
		handleCancel() {
			setOpenError(false);
		}
	}

  const onReset = () => {
    stageParams.current = { ...initParams };
    form.resetFields();
    setFilter([]);
    setLogisticSelect(0);
    setResetKey(restKey+1);
    quickSearchId && setQuickSearchId('');
  }

  const options1 = [
    { label: '超过12小时', value: 12 },
    { label: '超过24小时', value: 24 },
    { label: '超过36小时', value: 36 },
    { label: '超过48小时', value: 48 },
    { label: '超过72小时', value: 72 },
  ]

  const options2 = [
    { label: '发货后6小时内未揽收', value: 6 },
    { label: '发货后12小时内未揽收', value: 12 },
    { label: '发货后24小时内未揽收', value:24 },
    { label: '发货后36小时内未揽收', value: 36 },
    { label: '发货后72小时内未揽收', value: 72 },
  ]

  const onChange = (e)=>{
    if(e.target.checked){
      setCheckedList(errorList.reduce((prev,next)=>{
        return prev.concat(next.id);
      },[]))
    }else{
      setCheckedList([]);
    }
  }

  const errorShowText = useMemo(()=>{
    const len = checkedList?.length
    if(len){
     if(len == 1){
       const obj = find(errorList, ['id', checkedList[0]]);
       return obj.name;
     }else{
      let nums = 0;
      const list = staticNumberObj.errorList;
      checkedList.map(item=>{
        const obj = find(list, ['errorId', item]);
        nums += obj?.count || 0;
      })
      return `已选${len}种异常，订单数${nums} `
     }
    }
    return `异常订单 ${staticNumberObj.error || 0} `
  }, [checkedList, staticNumberObj])

  // useEffect(()=>{
  //   const len = checkedList?.length, isExit = filter.includes('errorIdArr');
  //   if((len && !isExit) || (!len && isExit)){
  //     handleChangeFilter('errorIdArr');
  //   }
  // }, [checkedList])

  const content = (<div style={{width: '508px', padding:'10px 10px'}}>

    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
      <Checkbox onChange={onChange} checked={statusObj.checked} indeterminate={statusObj.indeterminate}>全选 <span className='common-color2'>{checkedList?.length || ''}</span></Checkbox>
      <Button type="link" onClick={() => setOpenError(true)}>
        <Typography color="#0068FF"><ExclamationCircleOutlined /></Typography>
        &nbsp;&nbsp;<Typography color="#333">维护自定义异常</Typography>
      </Button>
    </div>
    <Checkbox.Group style={{ width: '100%' }} onChange={(e) => setCheckedList(e)} value={checkedList}>
      <Row>
        {
          errorList.map(item => {
            return (<Col span={8} key={item.id}>
              <Checkbox value={item.id}>{item.name}{item.count ? <span className='common-color2'>&nbsp;({item.count})</span> : ''}</Checkbox>
            </Col>)
          })
        }
      </Row>
    </Checkbox.Group>
   </div>)

  //改变超时时间
  const changeTimeOut = (type, value) => {
    stageParams.current[type] = value;
    if(filter.includes(type)){
      setFilter([...filter]);
    }
    !filter.includes(type) && getHotStatisticsFunc(value);
  }

  const hotGoodsSearchProps = {
    searchForm,
    hotGoodsCount: staticNumberObj.hotGoodsCount,
    handleOk(isOnlyContain, sysSkuCodeArr){
      handleSearch({
        ...searchForm,
        isOnlyContain,
        sysSkuCodeArr,
      })
    }
  }

  const judgeFixedRender = () => {
    if(type == 1){
      return (<>
      {/* <Button style={{height:'28px', marginRight: '8px'}}>被合并</Button> */}
      <SelectBtn onClick={()=>handleChangeFilter('auditCheck')} isSelect={filter.includes('auditCheck')}>待审核 {staticNumberObj?.noCheck || 0}</SelectBtn>
      <Popover placement="bottomLeft" content={content} trigger="hover" mouseEnterDelay={0.5} onOpenChange={(bool)=>bool && getErrorReasonFunc()}>
        <span><SelectBtn onClick={()=>handleChangeFilter('errorIdArr')} isSelect={filter.includes('errorIdArr')}>{errorShowText}<DownOutlined /></SelectBtn></span>
      </Popover>
     
      <SelectBtn onClick={()=>handleChangeFilter('mergeCheck')} isSelect={filter.includes('mergeCheck')}>被合并</SelectBtn>
      <SelectBtn onClick={()=>handleChangeFilter('splitCheck')} isSelect={filter.includes('splitCheck')}>被拆分</SelectBtn>
      <SelectBtn onClick={()=>handleChangeFilter('isMatchCheck')} isSelect={filter.includes('isMatchCheck')} style={{fontWeight: 600}}>
        未匹配<span className='common-color9'>供应商 {staticNumberObj.noMatch || 0}</span>
      </SelectBtn>

      <SelectBtn onClick={()=>handleChangeFilter('shipTimeOutCheck')} isSelect={filter.includes('shipTimeOutCheck')}>
        <div>
          <div style={{display:"inline-block", flex:1, marginRight:'8px', fontWeight: 600}}>
            发货<span className='common-color9'>快超时 {staticNumberObj.timeOutCount || 0}</span>
          </div>
          <div style={{display:"inline-block", flex:1, borderLeft: '1px solid #ddd'}}>
            <Select bordered={false} options={options1} defaultValue={12} showArrow={false} style={{width:'82px', textIndent:"3px"}} 
            dropdownMatchSelectWidth={120} onClick={e=>e.stopPropagation()}  onChange={e=>changeTimeOut('shipTimeOutCheck', e)}></Select>
          </div>
          <DownOutlined />
        </div>
      </SelectBtn>
      <Popover placement="top" content='付款后，超过XX时间未发货的订单'>
         <span><IconFont type='iconwenhao' style={{ cursor: 'pointer', fontSize: 16, position:'relative', top: '5px' }} /></span>
      </Popover>
      </>)
    }
    if(type == 2){
      return (<>
      <SelectBtn onClick={()=>handleChangeFilter('unpayCheck')} isSelect={filter.includes('unpayCheck')}>待付款 {staticNumberObj.noPayCount || 0}</SelectBtn>
      {/* <SelectBtn key={restKey}><HotGoodsSearch {...hotGoodsSearchProps} /></SelectBtn> */}
      <HotGoodsSearch key={restKey} {...hotGoodsSearchProps} />
      <SelectBtn onClick={()=>handleChangeFilter('printCheck1')} isSelect={filter.includes('printCheck1')} style={{fontWeight: 600}}>已打印<span className='common-color9'>未发货 {staticNumberObj.printNoShipCount || 0}</span></SelectBtn>
      <SelectBtn onClick={()=>handleChangeFilter('printCheck0')} isSelect={filter.includes('printCheck0')}>未打印</SelectBtn>
      <SelectBtn onClick={()=>handleChangeFilter('printCheck2')} isSelect={filter.includes('printCheck2')}>重复打印</SelectBtn>
      </>)
    }
    if(type == 3){
      return (<>
      <SelectBtn onClick={()=>handleChangeFilter('todayShipment')} isSelect={filter.includes('todayShipment')}>今日<span className='common-color9'>发货({staticNumberObj.shipToday || 0})</span></SelectBtn>
      <SelectBtn onClick={()=>handleChangeFilter('pickUpTimeOutCheck')} isSelect={filter.includes('pickUpTimeOutCheck')} hasPosition>
        <div>
          <div style={{display:"inline-block", flex:1, marginRight:'8px', fontWeight: 600}}>
            揽收<span className='common-color9'>快超时 {staticNumberObj.pickUpTimeOut || 0}</span>
          </div>
          <div style={{display:"inline-block", flex:1, borderLeft: '1px solid #ddd'}}>
            <Select bordered={false} options={options2} defaultValue={6} showArrow={false} style={{width:'140px', textIndent:"3px"}} 
            dropdownMatchSelectWidth={172} onClick={e=>e.stopPropagation()} onChange={e=>changeTimeOut('pickUpTimeOutCheck', e)}></Select>
          </div>
          <DownOutlined />
        </div>
      </SelectBtn>
      <Popover placement="top" content='发货后，超过XX时间未揽收的订单'>
         <span><IconFont type='iconwenhao' style={{ cursor: 'pointer', fontSize: 16, position:'relative', top: '5px' }} /></span>
      </Popover>
      </>)
    }
  }

  //点击快捷查询
  const handleClickQuickSearch = (value) => {
    const { id, param = '' } = value, obj = JSON.parse(param);
    stageParams.current = {
      ...initParams,
      ...(obj.stageParams || {}),
    }
    form.resetFields();
    setQuickSearchId(id);
    setResetKey(0);
    logisticSelect && setLogisticSelect(0);
  }

  const SortableItem = SortableElement(({ value }) => (
    <div style={{marginRight:6}} onClick={()=>handleClickQuickSearch(value)}>
    <QueryButton item={value} form={form} quickSearchId={quickSearchId} onClear={(val)=>handelDelete(val)} />
    </div>
  ));

  const SortableList = SortableContainer(({ items }) => {
    return (
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {items.map((value, index) => (
          <SortableItem key={`item-${index}`} index={index} value={value} />
        ))}
      </div>
    );
  });
  
  const submitAfterSortEnd = async ({ oldIndex, newIndex }) => {
   
    if(oldIndex == newIndex) return;
    const newItems = [...items];
    const [removedItem] = newItems.splice(oldIndex, 1);
    newItems.splice(newIndex, 0, removedItem);
    setItems(newItems);
    const arr = newItems.map((item,sort)=>({
      sort,
      id: item.id,
    }))
    await updateSortOp(arr);
};

const QuickSearchModalProps = {
  items,
  searchForm,
  stageParams,
  originFormData,
  page: 'hot-order',
  handleOk(){
    setVisible(false);
    handelGetConfigList();
  },
  handleCancel(){
    setVisible(false);
  }
}

  //检测表单是否有值
  const checkHasValue = (obj) => {
    Object.keys(obj).some(item=>{
      const currentValue = obj[item];
      if(typeof currentValue == 'undefined'){
        delete obj[item];
      }else if(Array.isArray(currentValue) && !currentValue?.length){
        delete obj[item];
      }else if(['provinceIdArr'].includes(item)){
        const bool = checkHasValue(currentValue);
        !bool && delete obj[item];
      }
    })
    return Boolean(Object.keys(obj)?.length)
  }

const handleSaveQuickSearch = () => {
  if(allQuickSearch.current?.length >= 20){
    return message.warn("搜索条件保存20个配置，请删除后再尝试");
  }
  const values = form.getFieldsValue(); 
  originFormData.current = {...cloneDeep(values), pageType: type };
  if(checkHasValue(values)){
    setVisible('QuickSearchModal');
  }else{
    notification.error({
      message: '请设置选项再保存',
      duration: null
    });
  }
}

  //重置 快捷查询表单载入后
  const handleFormLoad = (obj) => {
    const { defaultIds, zifaIds } = obj;
    warehouseGroup.current = { defaultIds: [...defaultIds], zifaIds: [...zifaIds] };
    stageParams.current.isLimit = false;
    if(quickSearchId){
      const quickItem = find(items, ['id', quickSearchId]);
      if(quickItem){
        const originFormData = JSON.parse(quickItem.param || '')?.originFormData || {};
        if(originFormData.time?.length){
          originFormData.time = [moment(originFormData.time[0]), moment(originFormData.time[1])];
        }
        console.log('originFormData', originFormData);
        form.setFieldsValue(originFormData);
      }
    }else{
      if(type == 2){
        form.setFieldsValue({
          warehouseIdArr: zifaIds
        })
      }
      // if(type == 1){
      //   return setFilter(['auditCheck', 'errorIdArr']);
      // }
    }
    setFilter([]);
  }

  const [update, setUpdate] = useState(0)
  const supplyStoreModalProps = {
    name: 'storeName',
    handleAllSelect(a){
      // console.log(a)
      // onChange(a);
      form.setFieldValue('storeName', a);
      setUpdate(update+1)
    }
  }

  //单个修改快递公司
  const handleSingleChangeExpress = (e)=>{
    const value = e.target.value;
    form.setFieldValue('logisticsCompanyId', value ? [value] : undefined);
    setLogisticSelect(value);
    setFilter([...filter])
  }

  const dealSpecChange = (type, value) => {
   if(type == 'logisticsCompanyId'){
    setLogisticSelect(0);
   }
  }

  return (<div ref={el}>
		{ openError && <ErrorTypeManageModal {...ErrorTypeManageProps} />}
    { visible == 'EditFilterModal' && <EditFilterModal {...EditFilterModalProps} />}
    { visible == 'QuickSearchModal' && <QuickSearchModal {...QuickSearchModalProps}/>}
    <div style={{ display: expand ? 'block' : 'none'}}>
      <div style={{display: 'flex', marginBottom:"12px"}}>
        {judgeFixedRender()}
      </div>
      {type == 2 && (<Radio.Group 
      style={{margin:'2px 0 8px 0', overflow:'hidden'}}
      onChange={handleSingleChangeExpress} 
      value={logisticSelect}>
      <Radio value={0}>全部</Radio>
      {
        staticNumberObj.logisticList?.map(item=>{
          return <Radio value={item.logisticId}>{item.logisticName} <span className='common-color2'> {item.count}</span></Radio>
        })
      }
    </Radio.Group>)}
      <Form
      form={form}
      name="basic"
      layout='inline'
      size='default'
      onFinish={()=>onFinish(true)}
      autoComplete="off"
    >
      <div className={styles.filter}>
      {
        filterList.filter(item=>item.checked).map(item => {
          const { name, slot, Component } = item
          if(allComponentsMap[name]){
            // if(name == 'storeName'){
            //   return <DynamicStoreSelectKX {...supplyStoreModalProps} />
            // }
            return (<Form.Item name={name} style={{width: name == 'time' ? (bigScreen ? '490px' : '447px') : (bigScreen ? '236px' : '215px'), marginBottom:'16px'}} key={name}>
              {slot || createElement(allComponentsMap[item.name], { stageParams, handleFormLoad, dealSpecChange })}
            </Form.Item>)
          }
        })
      }
      </div>
      <Form.Item>
        <Button
          type="primary"
          icon={<IconFont type="iconsousuo" style={{ fontSize: 14 }} />}
          htmlType="submit"
          style={{ marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={onReset} className="mb16 ml8" style={{order: 181}}><ReloadOutlined /> 重置</Button>
      </Form.Item>
    </Form>
      <div className={styles.quickSearchBox}>
        <div className={styles.quickSearchLeft}>
          <span>我的查询：</span>
          <SortableList
            axis="xy"
            items={items}
            onSortEnd={submitAfterSortEnd}
            hideSortableGhost={false}
            helperClass="row-dragging"
          />
        </div>
        <div className={styles.quickSearchRight}>
        <Button onClick={handleSaveQuickSearch}>另存为快捷查询</Button>
        <Button style={{ padding: 0, marginLeft: 12 }} type="link" onClick={() => setVisible('EditFilterModal')}>
          <IconFont type='iconshaixuan-primary' style={{fontSize:'14px', position:'relative', top: '2px', left: '4px'}} /> 筛选设置
        </Button>
        </div>
      </div>
    </div>
    <div className="toggle-search-form">
      <div className="toggle-search-form-target" onClick={()=>setExpand(!expand)}>
        {expand ? (
          <>
            <IconFont type="iconz045" />
            <span>收起</span>
          </>
        ) : (
          <>
            <IconFont type="iconzhankai" />
            <span>展开</span>
          </>
        )}
      </div>
    </div>
  </div>)
}